﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace 龙润数据采集
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        DAL.LongRunDAL DAL=new DAL.LongRunDAL();
        ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
        MesTool.Model.UserModel userModel = null;
        DispatcherTimer timer1 = new DispatcherTimer();
        Tool.KeyboardHook scanHook = new Tool.KeyboardHook();
        MesTool.UserBLL userBLL = new MesTool.UserBLL("192.168.2.3");
        string barcode = "";
        DateTime lastReadTime = DateTime.Now;
        public MainWindow()
        {
            InitializeComponent();
            DataContext = viewModel;
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            this.Left = 0;
            this.Top = 0;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Dictionary<string, string> dic = Tools.ConfigTool.ReadAll();
                TextBoxName.Text = dic["name"];
                ComboBoxPro.Text = dic["pro"];
                ComboBoxWkPosition.Text = dic["wkposition"];
                TextBoxPath.Text = dic["path"];
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = new TimeSpan(20000000);
                scanHook.BarCodeEvent += ScanHook_BarCodeEvent;
                PingCheck();
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
        }
        private void TextBoxPath_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择结果目录";
            //确认测试文件
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //选择路径
                string selectPath = dialog.SelectedPath;
                TextBoxPath.Text = selectPath;
            }
        }
        private void BorderStart_MouseMove(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void BorderStart_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }
        private void InsertDate(FileInfo fileInfo)
        {
            try
            {
                List<List<string>> data = new List<List<string>>();
                if (Tools.CsvTool.ReadCsv(fileInfo.FullName, out data) == false)
                {
                    HandyControl.Controls.Growl.Warning(fileInfo.FullName + "解析失败");
                    return;
                }
                int testCodeIndex, writeCodeIndex, timeIndex, resultIndex, revIndex, verIndex;
                testCodeIndex = data[0].IndexOf("测试码");
                writeCodeIndex = data[0].IndexOf("内部条码");
                timeIndex = data[0].IndexOf("测试时间");
                resultIndex = data[0].IndexOf("产品状态");
                revIndex = data[0].IndexOf("读取软件版本");
                verIndex = data[0].IndexOf("读取硬件版本");
                if (testCodeIndex == -1 || timeIndex == -1 || resultIndex == -1 || resultIndex == -1 || verIndex == -1)
                {
                    HandyControl.Controls.Growl.Warning(fileInfo.FullName + "解析失败");
                    return;
                }
                try
                {
                    var first = new Model.EcuDb.ECT_Test()
                    {
                        testCode = data[1][testCodeIndex].Trim(),
                        testTime = Convert.ToDateTime(data[1][timeIndex].Trim().Replace("-", " ")),
                        result = data[1][resultIndex].Trim(),
                        rev = data[1][revIndex].Trim(),
                        ver = data[1][verIndex].Trim(),
                        userName = userModel.nickName,
                    };
                    if (writeCodeIndex != -1)
                    {
                        first.writeCode = data[1][writeCodeIndex].Trim();
                    }
                    var last = new Model.EcuDb.ECT_Test()
                    {
                        testCode = data[data.Count - 1][testCodeIndex].Trim(),
                        testTime = Convert.ToDateTime(data[data.Count - 1][timeIndex].Trim().Replace("-", " ")),
                        result = data[data.Count - 1][resultIndex].Trim(),
                        rev = data[data.Count - 1][revIndex].Trim(),
                        ver = data[data.Count - 1][verIndex].Trim(),
                        userName = userModel.nickName,
                    };
                    if (writeCodeIndex != -1)
                    {
                        last.writeCode = data[data.Count - 1][writeCodeIndex].Trim();
                    }
                    if (DAL.Query(first) == false && DAL.Query(last) == false)
                    {
                        return;
                    }
                }
                catch (Exception)
                {
                }

                for (int i = data.Count - 1; i > 0; i--)
                {
                    Model.EcuDb.ECT_Test ect = null;
                    try
                    {
                        ect = new Model.EcuDb.ECT_Test()
                        {
                            testCode = data[i][testCodeIndex].Trim(),
                            testTime = Convert.ToDateTime(data[i][timeIndex].Trim().Replace("-", " ")),
                            result = data[i][resultIndex].Trim(),
                            rev = data[i][revIndex].Trim(),
                            ver = data[i][verIndex].Trim(),
                            userName = userModel.nickName,
                        };
                        if (writeCodeIndex!=-1)
                        {
                            ect.writeCode = data[i][writeCodeIndex].Trim();
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    if (DAL.Query(ect) == false)
                    {
                        continue;
                    }
                    while (DAL.Insert(ect) == false)
                    {
                        Thread.Sleep(500);
                    }
                    ListInsert(ect);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        private void CheckHistory()
        {
            try
            {
                string pro = "";
                string path = "";
                string user = "";
                Dispatcher.Invoke(() =>
                {
                    path = TextBoxPath.Text;
                    pro = ComboBoxPro.Text;
                    user = TextBoxName.Text;
                });
                DirectoryInfo directory = new DirectoryInfo(path);
                List<FileInfo> files = new List<FileInfo>();
                Tools.FileTool.GetDirectoryFiles(ref files, directory);
                files = files.OrderByDescending(it => it.LastWriteTime).ToList();
                lastReadTime = DateTime.Now;
                foreach (var item in files)
                {
                    if (item.FullName.Contains(".csv"))
                    {
                        InsertDate(item);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool PingCheck()
        {
            try
            {
                if (Tools.NetTool.Ping("192.168.2.2", 3000))
                {
                    ShieldSQL.Status = "连接正常";
                    ShieldSQL.Color = Brushes.SeaGreen;
                    return true;
                }
                else
                {
                    ShieldSQL.Status = "连接异常";
                    ShieldSQL.Color = Brushes.Tomato;
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        private void ListInsert(Model.EcuDb.ECT_Test ect)
        {

            if (List.Items.Count > 0
                && viewModel.Items[viewModel.Items.Count - 1].BackColor == Model.ColorModel.WaitColor
                && viewModel.Items[viewModel.Items.Count - 1].BarCode == ect.testCode)
            {
                Dispatcher.Invoke(() =>
                {
                    viewModel.Items[viewModel.Items.Count - 1].Time = ect.testTime.ToString("G");
                    viewModel.Items[viewModel.Items.Count - 1].BackColor = ect.result == "OK" ? Model.ColorModel.PassColor : Model.ColorModel.NgColor;
                    if (ect.result == "OK")
                    {
                        viewModel.Pass[0] += 1;
                    }
                    else
                    {
                        viewModel.Fail[0] += 1;
                    }
                });
                return;
            }
            Dispatcher.Invoke(() =>
            {
                ViewModel.MainViewModel.Item item = new ViewModel.MainViewModel.Item()
                {
                    No = viewModel.Items.Count + 1,
                    BarCode = ComboBoxPro.Text.Contains("J80J3_B") ? ect.testCode : ect.writeCode,
                };
                if (String.IsNullOrEmpty(ect.result) == false)
                {
                    item.BackColor = ect.result == "OK" ? Model.ColorModel.PassColor : Model.ColorModel.NgColor;
                    item.Time = ect.testTime.ToString("G");
                    if (ect.result == "OK")
                    {
                        viewModel.Pass[0] += 1;
                    }
                    else
                    {
                        viewModel.Fail[0] += 1;
                    }
                }
                else
                {
                    item.BackColor = Model.ColorModel.WaitColor;
                    item.Time = "";
                }
                viewModel.Items.Add(item);
                List.ScrollIntoView(List.Items[item.No - 1]);
            });
        }
        bool isUp=false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (PingCheck()==false)
                {
                    return;
                }
                if(isUp)
                {
                    return;
                }
                isUp = true;
                string pro = "";
                string path = "";
                string user = "";
                Dispatcher.Invoke(() =>
                {
                    path = TextBoxPath.Text;
                    pro = ComboBoxPro.Text;
                    user = TextBoxName.Text;
                });
                DirectoryInfo directory = new DirectoryInfo(path);
                List<FileInfo> files = new List<FileInfo>();
                Tools.FileTool.GetDirectoryFiles(ref files, directory);
                var file = files.Where(it => it.LastWriteTime > lastReadTime).ToList(); 
                lastReadTime = DateTime.Now;
                foreach (var item in file)
                {
                    if (item.FullName.Contains(".csv"))
                    {
                        InsertDate(item);
                    }
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
            finally 
            { 
                isUp = false; 
            }
        }
        private void BorderStart_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (PackIconStart.Kind == MaterialDesignThemes.Wpf.PackIconKind.Play)
                {
                    if (TextBoxPath.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择结果目录!");
                        return;
                    }
                    if (TextBoxName.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先输入工号!");
                        return;
                    }
                    if (ComboBoxPro.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择产品!");
                        return;
                    }
                    if (ComboBoxWkPosition.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择工序!");
                        return;
                    }
                    string err = "";
                    userModel = userBLL.GetDingTalkUserModel(TextBoxName.Text.Trim());
                    if (userModel == null)
                    {
                        HandyControl.Controls.MessageBox.Error(err);
                        return;
                    }
                    TextBoxName.Text = userModel.nickName;
                    viewModel.Enable = false;
                    BorderStart.Background = Model.ColorModel.NgColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Stop;
                    PoptipStart.Content = "停止采集";
                    CheckHistory();
                    timer1.Start();
                    if (ComboBoxPro.Text.Contains("J80J3_B"))
                    {
                        scanHook.Start();
                    }
                }
                else
                {
                    if (userModel != null)
                    {
                        TextBoxName.Text = userModel.userName;
                    }
                    viewModel.Enable = true;
                    BorderStart.Background = Model.ColorModel.OkColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                    PoptipStart.Content = "开始采集";
                    timer1.Stop();
                    if (ComboBoxPro.Text.Contains("J80J3_B"))
                    {
                        scanHook.Stop();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.ToString());
                }
                viewModel.Enable = true;
                BorderStart.Background = Model.ColorModel.OkColor;
                PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                PoptipStart.Content = "开始采集";
                timer1.Stop();
                scanHook.Stop();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Tools.ConfigTool.Write("wkposition", ComboBoxWkPosition.Text);
            Tools.ConfigTool.Write("pro", ComboBoxPro.Text);
            Tools.ConfigTool.Write("path", TextBoxPath.Text);
            if (userModel != null)
            {
                Tools.ConfigTool.Write("name", userModel.userName);
            }
            System.Environment.Exit(0);
        }

        private void ScanHook_BarCodeEvent(Tool.KeyboardHook.InputCodes barCode)
        {
            try
            {
                barcode = barCode.InputStr;
                //todo新增
                if (barcode.Contains("J80J3"))
                {
                    Model.EcuDb.ECT_Test ect = new Model.EcuDb.ECT_Test()
                    {
                        testCode=barcode,
                    };
                    ListInsert(ect);
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
        }
    }
}
